package com.nmgydy.screen.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nmgydy.beans.ListBean;
import com.nmgydy.beans.ResultBean;
import com.nmgydy.model.Admin;
import com.nmgydy.model.EventItem;
import com.nmgydy.model.Module;
import com.nmgydy.model.Role;
import com.nmgydy.util.BpmnUtil;
import com.nmgydy.util.Functions;
import com.nmgydy.util.HibernateDao;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/screen")
public class ScreenController {

	@Resource
	private HibernateDao hibernateDao;

	@RequestMapping(value = "overview", method = RequestMethod.GET)
	public String list(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/screen/overview";
	}

	//法官案件情况统计
	@RequestMapping(value = "userData", method = RequestMethod.POST)
	@ResponseBody
	public String userData(HttpServletRequest request, HttpServletResponse response, Model model) {
		Session session = null;
		try {
			//开始数据库操作
			session = hibernateDao.getSessionFactory().openSession();
			String sql = "select userId,userName," +
					" count(*) as total," +
					" sum(case when status='1' then 1 end) as total1," +
					" sum(case when status='2' then 1 end) as total2," +
					" sum(case when status='3' then 1 end) as total3" +
					" from cn_court group by userId order by total desc limit 15";
			List<?> list = session.createSQLQuery(sql)
					.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
					.list();
			return JSON.toJSONString(new ListBean(list));
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(ResultBean.failure("查询失败"));
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}


	//案件概况
	@RequestMapping(value = "courtData", method = RequestMethod.POST)
	@ResponseBody
	public String courtData(String status,HttpServletRequest request, HttpServletResponse response, Model model) {
		Session session = null;
		try {
			//开始数据库操作
			session = hibernateDao.getSessionFactory().openSession();
			String sql = "select count(*) as total," +
					" sum(case when status='1' then 1 end) as total1," +
					" sum(case when status='2' then 1 end) as total2," +
					" sum(case when status='3' then 1 end) as total3," +
					" sum(case when caseType='1' then 1 end) as typeTot1," +
					" sum(case when caseType='2' then 1 end) as typeTot2," +
					" sum(case when caseType='3' then 1 end) as typeTot3" +
					" from cn_court";

			if(!Functions.isEmpty(status)){
				sql += " where status=:status";
			}
			Query query = session.createSQLQuery(sql)
					.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			if(!Functions.isEmpty(status)){
				query.setParameter("status",status);
			}
			List<?> list = query.list();
			Map<String,Object> row = (Map<String, Object>) list.get(0);
			row.putIfAbsent("total1", 0);
			row.putIfAbsent("total2", 0);
			row.putIfAbsent("total3", 0);
			row.putIfAbsent("typeTot1", 0);
			row.putIfAbsent("typeTot2", 0);
			row.putIfAbsent("typeTot3", 0);
			BigDecimal big100 = new BigDecimal(100);
			BigDecimal totalBig = new BigDecimal(String.valueOf(row.get("total")));
			BigDecimal typeTot1Big = new BigDecimal(String.valueOf(row.get("typeTot1")));
			BigDecimal typeTot2Big = new BigDecimal(String.valueOf(row.get("typeTot2")));
			BigDecimal typeTot3Big = new BigDecimal(String.valueOf(row.get("typeTot3")));
			row.put("typeRate1",typeTot1Big.multiply(big100).divide(totalBig,2,BigDecimal.ROUND_CEILING));
			row.put("typeRate2",typeTot2Big.multiply(big100).divide(totalBig,2,BigDecimal.ROUND_CEILING));
			row.put("typeRate3",typeTot3Big.multiply(big100).divide(totalBig,2,BigDecimal.ROUND_CEILING));
			return JSON.toJSONString(ResultBean.success(row));
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(ResultBean.failure("查询失败"));
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	//案件趋势
	@RequestMapping(value = "courtTrendData", method = RequestMethod.POST)
	@ResponseBody
	public String courtTrendData(HttpServletRequest request, HttpServletResponse response, Model model) {
		Session session = null;
		try {
			//开始数据库操作
			session = hibernateDao.getSessionFactory().openSession();
			String sql = "select substr(createTime,1,10) as dateStr," +
					" count(*) as total," +
					" sum(case when caseType='1' then 1 end) as typeTot1," +
					" sum(case when caseType='2' then 1 end) as typeTot2," +
					" sum(case when caseType='3' then 1 end) as typeTot3" +
					" from cn_court group by dateStr order by dateStr desc limit 7";

			Query query = session.createSQLQuery(sql)
					.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			List<?> list = query.list();

			for(int i=0;i<list.size();i++){
				Map<String,Object> row = (Map<String, Object>) list.get(i);
				row.putIfAbsent("typeTot1", 0);
				row.putIfAbsent("typeTot2", 0);
				row.putIfAbsent("typeTot3", 0);
			}

			return JSON.toJSONString(new ListBean(list));
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(ResultBean.failure("查询失败"));
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	//案件节点逾期排行分析
	@RequestMapping(value = "overdueData", method = RequestMethod.POST)
	@ResponseBody
	public String overdueData(HttpServletRequest request, HttpServletResponse response, Model model) {
		Session session = null;
		try {
			//开始数据库操作
			session = hibernateDao.getSessionFactory().openSession();
			String sql = "select taskId,taskName," +
					" count(*) as total," +
					" sum(case when status='1' then 1 end) as total1," +
					" sum(case when status='2' then 1 end) as total2," +
					" sum(case when status='3' then 1 end) as total3" +
					" from cn_move_history group by taskId" +
					" order by total3 desc limit 15";
			List<?> list = session.createSQLQuery(sql)
					.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
					.list();

			BigDecimal big100 = new BigDecimal(100);
			for(int i=0;i<list.size();i++){
				Map<String,Object> row = (Map<String, Object>) list.get(i);
				row.putIfAbsent("total3", 0);
				BigDecimal overdueRate = new BigDecimal(String.valueOf(row.get("total3")))
						.multiply(big100)
						.divide(new BigDecimal(String.valueOf(row.get("total"))),2,BigDecimal.ROUND_CEILING);
				row.put("overdueRate", overdueRate);
			}

			return JSON.toJSONString(new ListBean(list));
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(ResultBean.failure("查询失败"));
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	//近期事件
	@RequestMapping(value = "eventData", method = RequestMethod.POST)
	@ResponseBody
	public String eventData(String eventType, HttpServletRequest request, HttpServletResponse response, Model model) {
		Session session = null;
		try {
			//开始数据库操作
			session = hibernateDao.getSessionFactory().openSession();
			String sql = "select * from cn_event_item where eventType=:eventType order by id desc limit 5";
			List<?> list = session.createSQLQuery(sql)
					.setParameter("eventType",eventType)
					.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
					.list();

			return JSON.toJSONString(new ListBean(list));
		} catch (Exception e) {
			e.printStackTrace();
			return JSON.toJSONString(ResultBean.failure("查询失败"));
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

}
